<!-- eslint-disable vue/no-template-shadow -->
<!--
 * @Description: 设备管理管理页面
-->
<template>
  <!-- <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar :add-active="addActive" :del-active="delActive" :page-no="171" @add="add" @del="del" />
    </template>
<template v-slot:tab-select>
      <SelectButton :buttonselectlist="buttonselectlist" @topitemtype="topitemtype" />
    </template>
<template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">设备名称:</div>
          <div class="input">
            <el-input v-model="equipmentName" clearable @change="search" />
          </div>
        </div>
      </SearchBox>
    </template>
<template v-slot:table-box>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border height="88%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="equipmentName" label="设备名称" />
        <el-table-column prop="equipmentTypeStr" label="设备类型" />
        <el-table-column prop="rtuId" label="RTUId" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.equipmentId" slot-scope="scope">
            <el-button v-if="judgePermission(171, 'edit')" class="text-btn-cursor" type="text" size="small"
              @click="edit(scope.row)">修 改</el-button>
            <el-button v-if="judgePermission(171, 'delete')" class="text-btn-cursor cursor-delete" type="text"
              size="small" @click="handleDelete(scope.row.equipmentId)">删 除</el-button>
            <el-button class="text-btn-cursor" type="text" size="small" @click="restartRUT(scope.row.rtuId)">重
              启</el-button>
          </template>
</el-table-column>
</el-table>
<Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize"
  @changeCurrentPage="changeCurrentPage" />
</template>
<template v-slot:dialog>
    </template>
</BaseMainSlot> -->

  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="search">
      </SearchForm>
    </template>
    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="buttonselectlist" :labelKey="'value'">
      </EnumSlot>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border height="88%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="equipmentName" label="设备名称" />
        <el-table-column prop="equipmentTypeStr" label="设备类型" />
        <el-table-column prop="rtuId" label="RTUId" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.equipmentId" slot-scope="scope">
            <el-button v-if="judgePermission(171, 'edit')" class="text-btn-cursor" type="text" size="small"
              @click="edit(scope.row)">修 改</el-button>
            <el-button v-if="judgePermission(171, 'delete')" class="text-btn-cursor cursor-delete" type="text"
              size="small" @click="handleDelete(scope.row.equipmentId)">删 除</el-button>
            <el-button class="text-btn-cursor" type="text" size="small" @click="restartRUT(scope.row.rtuId)">重
              启</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal='false' :title="titleText + '设备信息'" :visible.sync="dialogFormVisible"
        @close="cancel">
        <el-form ref="formData" :model="formData" :rules="rules" label-width="120px" class="demo-ruleForm">
          <el-form-item label="物联设备选择" prop="rtuId" >
            <el-select class="w100p" filterable clearable v-model="formData.rtuId" placeholder="请选择物联设备" @change="depDataItem">
              <el-option v-for="item in dataItemList" :key="item.rtuId" :label="item.rtuName" :value="item.rtuId" />
            </el-select>
          </el-form-item>
          <el-form-item label="物联设备名称" prop="equipmentName" >
            <el-input v-model="formData.equipmentName" placeholder="请输入设备名称" clearable />
          </el-form-item>
          <el-form-item label="设备编号" prop="equipmentCode" >
            <el-input v-model="formData.equipmentCode" placeholder="请输入设备编号" clearable />
          </el-form-item>
          <el-form-item label="设备类型" prop="equipmentType" >
            <el-select class="w100p" filterable clearable v-model="formData.equipmentType" placeholder="请选择设备类型">
              <el-option v-for="item in buttonselectlist" :key="item.value" :label="item.value" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark" >
            <el-input v-model="formData.remark" clearable :rows="2" type="textarea" placeholder="请输入描述" />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>

import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import BtnSlot from '@/components-production-management/BtnSlot';
import EnumSlot from '@/components-production-management/EnumSlot';

import ActionBar from "@/components/ActionBar";
import DeviceManagementApi from "@/api/basic-info-manage/device-management";
import EnumApi from "@/api/enum";
import SelectButton from "./selectbutton/index.vue";
import SearchBox from "@/components/SearchBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import axios from "axios";
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "dataManagement",
  components: { Pagination, SelectButton, BaseMainSlot, SearchBox, ActionBar, BtnSlot, SearchForm, MainSlot, EnumSlot },
  mixins: [mymixin],
  data() {
    return {
      unfoldFlag: false,
      loading: false,
      selectIndex: 0,
      btnList: ['add', 'delete'],
      buttonselectlist: [
        { name: "WEATHERSTATION", value: "气象站" },
        { name: "AERATOR", value: "增氧机" },
        { name: "SENSOR", value: "传感器" },
        { name: "FEEDER", value: "投料机" }
      ],
      dataItemList: [],
      rules: {
        rtuId: [
          { required: true, message: "请选择物联设备", trigger: ["change", "blur"] }
        ],
        equipmentName: [
          { required: true, message: "请输入物联设备名称", trigger: ["change", "blur"] }
        ],
        equipmentType: [
          { required: true, message: "请选择设备类型", trigger: ["change", "blur"] }
        ],
      },
      // 选中的鱼塘id数组 ID组成
      incomeCostIdList: [],
      dialogFormVisible: false,
      batchVo: {},
      facilityVoList: [],
      scope: "",
      equipmentName: "",
      topitemType: "",
      dataTreeItemList: [],
      options: [],
      formItemList: [
        {
          label: '设备名称',
          type: 'input',
          selectOptions: [],
          param: 'equipmentName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    dialogFormVisible(v) {
      if (v) {
        this.$nextTick(() => {
          this.$refs['formData'].clearValidate()
        })
      }
    }
  },
  created() {
    // 获取设备类型
    this.queryEnum();
    // 获取当前基地所有设备
    this.ownership();

  },
  mounted() { },
  methods: {
    getEnumEvent(enumInfo) {
      let { data, index } = enumInfo;
      this.topitemType = data.name;
      this.selectIndex = index;
      this.tableData = [];
      this.getTableDataList();
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.add();
      } else if (flag == 'delete') {
        this.delmessage()
      }
    },
    //重启RTU
    restartRUT(RTUid) {
      let url = 'http://fishery.ssagroup.cn:8080/iotApplication/rtuControl/reboot'
      RTUid && axios.post(url, { rtuId: RTUid }).then(res => {
        this.$message.success('RTU重启中...')
        console.log(res)
      })
    },
    topitemtype(e) {
      this.topitemType = e;
      // 获取表格数据
      this.tableData = [];
      this.getTableDataList();
    },
    // 获取设备类型
    queryEnum() {
      EnumApi.list({ enumType: "EquipmentType" }).then(res => {
        if (res.success) {
          this.buttonselectlist = res.data;
          this.getEnumEvent({
            data: this.buttonselectlist[0],
            index: 0
          });
        }
      });
    },
    // 获取表格数据
    getTableDataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          equipmentType: this.topitemType,
          equipmentName: this.equipmentName
        }
      };
      this.loading = true;
      DeviceManagementApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
        }
      });
    },
    ownership() {
      DeviceManagementApi.queryRtuByCompanyMark().then(res => {
        let data = res.data;
        this.dataItemList = data;
      });
    },
    // 循环过滤树形数组
    filterArrForKey(arr) {
      let newArr = [];
      // console.log(arr)
      if (arr == [] || arr === undefined || arr[0] === undefined) {
        return;
      }
      newArr = arr.map(item => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey(item.child)
          };
        } else {
          delete item.child;
        }
        return item;
      });
      newArr = newArr.filter(item => item != null);
      return newArr;
    },
    // 选择物联设备
    depDataItem(e) {
      console.log(e);
      let index = this.dataItemList.findIndex(b => b.rtuId === e);
      let form = { ...this.dataItemList[index] };
      this.$set(this.formData, "equipmentName", form.rtuName);
    },
    search(data) {
      this.currentPage = 1;
      this.equipmentName = data.equipmentName
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleSelectionChange(list) {
      this.incomeCostIdList = [];
      this.incomeCostIdList = list.map(item => item.equipmentId);
      if (this.incomeCostIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      if (!this.incomeCostIdList.length) return;
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          DeviceManagementApi.delListById({ idList: this.incomeCostIdList }).then(res => {
            if (res.success) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.warning("删除失败");
            }
          }
          );
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          DeviceManagementApi.delById({ id: val }).then(res => {
            if (res.success) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.warning(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    edit(row) {
      this.formData = { ...row };
      this.nowChanceStau = "edit";
      this.titleText = "修改";
      this.dialogFormVisible = true;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            DeviceManagementApi.edit(this.formData).then(res => {
              if (res.success) {
                this.cancel()
                this.$message.success("修改成功！");
                this.getTableDataList();
              } else if (res.success && res.code === 200) {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            DeviceManagementApi.add(this.formData).then(res => {
              if (res.success) {
                this.cancel()
                this.$message.success("新增成功！");
                this.getTableDataList();
              } else {
                this.$message.error(res.message || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss"></style>
